<template>
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="visible" class="modal-overlay" @click="$emit('update:visible', false)">
        <div class="modal-content box-radius" @click.stop>
          <!-- 模态框头部 -->
          <div class="modal-header">
            <h3>个人资料</h3>
            <button class="close-btn" @click="$emit('update:visible', false)">
              <PhX :size="20" weight="bold" />
            </button>
          </div>

          <!-- 模态框内容 -->
          <div class="modal-body">
            <form class="profile-form" @submit.prevent="handleSubmit" novalidate>
              <!-- 头像上传区域 -->
              <div class="avatar-section">
                <div class="avatar-wrapper">
                  <img :src="formData.avatar || '/src/assets/default-avatar.png'" alt="avatar">
                  <div class="avatar-overlay" @click="triggerUpload">
                    <PhCamera :size="20" weight="bold" />
                    <span>更换头像</span>
                  </div>
                </div>
                <input
                  type="file"
                  ref="fileInput"
                  accept="image/*"
                  style="display: none"
                  @change="handleAvatarChange"
                >
              </div>

              <!-- 表单项 -->
              <div class="form-item">
                <input
                  v-model="formData.nickname"
                  type="text"
                  placeholder="昵称"
                  required
                  :class="{ error: errors.nickname }"
                  @blur="validateNickname"
                >
                <span v-if="errors.nickname" class="error-message">
                  <i class="fas fa-exclamation-circle"></i>
                  {{ errors.nickname }}
                </span>
              </div>

              <div class="form-item">
                <textarea
                  v-model="formData.signature"
                  placeholder="个性签名"
                  rows="3"
                  :class="{ error: errors.signature }"
                  @blur="validateSignature"
                ></textarea>
                <span v-if="errors.signature" class="error-message">
                  <i class="fas fa-exclamation-circle"></i>
                  {{ errors.signature }}
                </span>
              </div>

              <div class="form-tips">
                <p>完善的个人资料有助于其他用户了解你</p>
              </div>

              <button type="submit" class="submit-btn" :disabled="saving">
                {{ saving ? '保存中...' : '保存修改' }}
              </button>
            </form>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { PhX, PhCamera } from '@phosphor-icons/vue';
import { useUserStore } from '@/stores';
import Message from '@/components/message';
import { uploadFile } from '@/api/file';

// Props & Emits
const props = defineProps<{
  visible: boolean
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean]
}>();

// Store & Refs
const userStore = useUserStore();
const fileInput = ref<HTMLInputElement | null>(null);
const saving = ref(false);

// Form Data & Validation
const formData = reactive({
  id: '',
  nickname: '',
  signature: '',
  avatar: '',
});

const errors = reactive({
  nickname: '',
  signature: ''
});

// 重置表单数据和错误状态
const resetForm = () => {
  // 每次重置时从 userStore 获取最新数据
  formData.id = userStore.id || '';
  formData.avatar = userStore.avatar || '';
  formData.nickname = userStore.nickname || '';
  formData.signature = userStore.signature || '';
  errors.nickname = '';
  errors.signature = '';
};

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm();
  }
});

// Validation Methods
const validateNickname = () => {
  if (!formData.nickname.trim()) {
    errors.nickname = '请输入昵称';
  } else if (formData.nickname.length < 2) {
    errors.nickname = '昵称至少需要2个字符';
  } else {
    errors.nickname = '';
  }
};

const validateSignature = () => {
  if (formData.signature.length > 200) {
    errors.signature = '个性签名不能超过200字';
  } else {
    errors.signature = '';
  }
};

// Avatar Methods
const triggerUpload = () => {
  fileInput.value?.click();
};

const handleAvatarChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (!target.files?.length) return;

  const file = target.files[0];
  if (file.size > 5 * 1024 * 1024) {
    Message.error('图片大小不能超过 5MB');
    return;
  }

  try {
    // 这里添加上传头像的逻辑
    const uploadFormData = new FormData();
    uploadFormData.append('file', file);
    uploadFormData.append('category', 'avatar');
    const result = await uploadFile(uploadFormData);
    formData.avatar = result.data.src;
    if(result.errorCode === 0){
      Message.success('上传成功');
    }else {
      Message.error(result.data.error);
    }

  } catch (error) {
    throw error;
  }
};

// Form Submit
const handleSubmit = async () => {
  if (saving.value) return;

  // 验证表单
  validateNickname();
  validateSignature();

  if (errors.nickname || errors.signature) return;

  try {
    saving.value = true;
    console.log('formData',formData);
    await userStore.updateProfile(formData);
    emit('update:visible', false);
  }finally {
    saving.value = false;
  }
};
</script>
<style lang="less" scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
  }

  .close-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border: none;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    transition: all 0.2s;

    &:hover {
      background: #f1f5f9;
      color: #1f2937;
    }
  }
}

.modal-body {
  padding: 24px;
}

.profile-form {
  .avatar-section {
    margin-bottom: 24px;
    display: flex;
    justify-content: center;

    .avatar-wrapper {
      position: relative;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      overflow: hidden;
      cursor: pointer;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .avatar-overlay {
        position: absolute;
        inset: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: white;
        opacity: 0;
        transition: opacity 0.2s;
        gap: 4px;

        span {
          font-size: 12px;
        }

        &:hover {
          opacity: 1;
        }
      }
    }
  }

  .form-item {
    margin-bottom: 24px;
    position: relative;

    input, textarea {
      width: 100%;
      box-sizing: border-box;
      padding: 12px 16px;
      border: 1px solid #e2e8f0;
      border-radius: 8px;
      font-size: 14px;
      transition: all 0.2s;

      &:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }

      &.error {
        border-color: #ef4444;

        &:focus {
          box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }
      }
    }

    textarea {
      resize: vertical;
      min-height: 80px;
    }

    .error-message {
      position: absolute;
      left: 0;
      bottom: -20px;
      font-size: 12px;
      color: #ef4444;
      display: flex;
      align-items: center;
      gap: 4px;
      opacity: 0;
      transform: translateY(-5px);
      animation: slideIn 0.3s ease forwards;

      i {
        font-size: 14px;
      }
    }
  }

  .form-tips {
    padding: 12px;
    background: #f8fafc;
    border-radius: 8px;
    margin-bottom: 24px;

    p {
      margin: 0;
      font-size: 13px;
      color: #64748b;
    }
  }

  .submit-btn {
    width: 100%;
    height: 40px;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;

    &:hover:not(:disabled) {
      background: #2563eb;
    }

    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }
}

// 动画
@keyframes slideIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 深色模式
@media (prefers-color-scheme: dark) {
  .modal-content {
    background: #1f2937;
  }

  .modal-header {
    border-bottom-color: #374151;

    h3 {
      color: #e5e7eb;
    }

    .close-btn {
      color: #9ca3af;

      &:hover {
        background: #374151;
        color: #e5e7eb;
      }
    }
  }

  .profile-form {
    .form-item {
      input, textarea {
        background: #374151;
        border-color: #4b5563;
        color: #e5e7eb;

        &::placeholder {
          color: #9ca3af;
        }

        &:hover {
          border-color: #6b7280;
        }

        &:focus {
          border-color: #60a5fa;
          box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1);
        }

        &.error {
          border-color: #f87171;

          &:focus {
            box-shadow: 0 0 0 3px rgba(248, 113, 113, 0.1);
          }
        }
      }

      .error-message {
        color: #f87171;
      }
    }

    .form-tips {
      background: #374151;

      p {
        color: #9ca3af;
      }
    }
  }
}
</style>
